import { defineStore } from 'pinia'
import { v4 as uuidv4 } from 'uuid'

export const useTaskStore = defineStore('tasks', {
  state: () => ({
    tasks: [],
    loading: false,
    error: null
  }),
  getters: {
    // 获取所有未删除的任务
    allTasks: (state) => state.tasks.filter(task => !task.deleted),
    
    // 获取今日任务
    todayTasks: (state) => {
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      
      return state.tasks.filter(task => {
        if (task.deleted) return false
        if (!task.dueDate) return false
        
        const dueDate = new Date(task.dueDate)
        dueDate.setHours(0, 0, 0, 0)
        
        return dueDate.getTime() === today.getTime()
      })
    },
    
    // 按分类获取任务
    getTasksByCategory: (state) => (categoryId) => {
      return state.tasks.filter(task => !task.deleted && task.categoryId === categoryId)
    },
    
    // 按完成状态获取任务
    getTasksByStatus: (state) => (completed) => {
      return state.tasks.filter(task => !task.deleted && task.completed === completed)
    }
  },
  actions: {
    // 添加新任务
    addTask(taskData) {
      const newTask = {
        id: uuidv4(),
        title: taskData.title,
        description: taskData.description || '',
        completed: false,
        createdAt: new Date(),
        updatedAt: new Date(),
        dueDate: taskData.dueDate || null,
        reminder: taskData.reminder || null,
        priority: taskData.priority || 'medium',
        categoryId: taskData.categoryId,
        deleted: false
      }
      
      this.tasks.push(newTask)
      this.saveTasks()
      return newTask
    },
    
    // 更新任务
    updateTask(id, updatedData) {
      const taskIndex = this.tasks.findIndex(task => task.id === id)
      
      if (taskIndex !== -1) {
        this.tasks[taskIndex] = {
          ...this.tasks[taskIndex],
          ...updatedData,
          updatedAt: new Date()
        }
        this.saveTasks()
        return true
      }
      
      return false
    },
    
    // 切换任务完成状态
    toggleTaskCompletion(id) {
      const task = this.tasks.find(task => task.id === id)
      
      if (task) {
        task.completed = !task.completed
        task.updatedAt = new Date()
        this.saveTasks()
        return true
      }
      
      return false
    },
    
    // 删除任务（软删除）
    deleteTask(id) {
      const task = this.tasks.find(task => task.id === id)
      
      if (task) {
        task.deleted = true
        task.updatedAt = new Date()
        this.saveTasks()
        return true
      }
      
      return false
    },
    
    // 永久删除任务
    permanentlyDeleteTask(id) {
      const taskIndex = this.tasks.findIndex(task => task.id === id)
      
      if (taskIndex !== -1) {
        this.tasks.splice(taskIndex, 1)
        this.saveTasks()
        return true
      }
      
      return false
    },
    
    // 加载任务
    async loadTasks() {
      this.loading = true
      this.error = null
      
      try {
        // 这里将来会使用Tauri的文件系统API读取任务数据
        // 暂时使用localStorage模拟
        const tasksData = localStorage.getItem('todo_tasks')
        if (tasksData) {
          this.tasks = JSON.parse(tasksData)
        }
      } catch (err) {
        console.error('加载任务失败:', err)
        this.error = '加载任务失败'
      } finally {
        this.loading = false
      }
    },
    
    // 保存任务
    saveTasks() {
      try {
        // 这里将来会使用Tauri的文件系统API保存任务数据
        // 暂时使用localStorage模拟
        localStorage.setItem('todo_tasks', JSON.stringify(this.tasks))
      } catch (err) {
        console.error('保存任务失败:', err)
        this.error = '保存任务失败'
      }
    }
  }
}) 